<?php
/**
*	控制器
*/
namespace Rainrock\Framework\kernel\core;

use Rainrock\Framework\kernel\base\Session;
use Rainrock\Framework\kernel\base\Auth;
use Rainrock\Framework\kernel\base\Base;
use Rainrock\Framework\kernel\base\Request;
use Rainrock\Framework\kernel\Html\HtmlLabel;

class Controller extends BaseClass{
	
	/**
	*	设置header
	*/
	protected final function addHeader($key, $val='')
	{
		if($val)$key .= ': '.$val.'';
		Header($key);
	}
	
	/**
	*	设置Content-type
	*/
	protected final function setContenttype($val)
	{
		$this->addHeader('Content-type', $val);
	}
	
	/**
	*	跳转
	*/
	protected final function location($url)
	{
		$this->addHeader('location', $url);
	}
	
	/**
	*	跨域请求的
	*/
	protected final function accessControlAllow()
	{
		$laiyuan 	= Request::get('laiyuan');
		if($laiyuan == 'web'){
			$this->addHeader('Access-Control-Allow-Origin', '*');
			$this->addHeader('Access-Control-Allow-Headers', 'X-Requested-With');
			$this->addHeader('Access-Control-Allow-Credentials', 'true');
		}
		if(Request::type()=='OPTIONS')return $this->returnsuccess('ok');
	}
	
	/**
	*	获取登录信息
	*/
	public final function getAuth()
	{
		$tokenid = (int)Session::get('tokenid','0');
		$where 	 = '`id`='.$tokenid.'';
		
		$token 	 = Request::param('token');
		if($token)$where = "`token`='$token'";
		
		$tokenrs = $this->m('systoken')->getone(''.$where.' AND `online`=1');
		if(!$tokenrs)return false;
		if($tokenid != $tokenrs['id']){
			Session::set('tokenid', $tokenrs['id']);
		}
		$uid 	 = (int)$tokenrs['uid'];
		$urs 	 = $this->m(Base::getConfig('admintable'))->getone('`id`='.$uid.' AND `status`=1');
		if(!$urs)return false;
		Auth::setUserInfo($urs);
		return true;
	}
	
	/**
	*	模版显示
	*/
	public final function View()
	{
		return new View();
	}

	/**
	*	标签创建
	*/
	public final function Label($lx='')
	{
		return HtmlLabel::get($lx);
	}	
	
	/**
	*	初始化控制器
	*/
	public function initController() { }
	
	/**
	*	处理完成后
	*/
	public function onControllerAfter($barr)
	{
		$logid	= Request::param('syslogid');
		if($logid){
			$bstr 	= '';
			if(is_array($barr))$bstr  = json_encode($barr, JSON_UNESCAPED_UNICODE);
			if(is_string($barr))$bstr = $barr;
			$this->m('syslog')->update(array(
				'result' => $bstr,
				'lastdt' => date('Y-m-d H:i:s')
			), $logid);
		}
	}

	
	/**
	*	验证登录
	*/
	public function checkAccess()
	{
		
	}
	
	
	/**
	*	默认首页的方法
	*/
	public function indexAction()
	{
		return ''.CONTROLLER.' index not dev';
	}
}